/*
 * @(#)ClbApi.java   1.0  2021年9月13日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.register.alclb.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.slb20140515.models.AddVServerGroupBackendServersRequest;
import com.aliyun.slb20140515.models.AddVServerGroupBackendServersResponse;
import com.aliyun.slb20140515.models.CreateRulesRequest;
import com.aliyun.slb20140515.models.CreateRulesResponse;
import com.aliyun.slb20140515.models.CreateVServerGroupRequest;
import com.aliyun.slb20140515.models.CreateVServerGroupResponse;
import com.aliyun.slb20140515.models.DescribeRulesRequest;
import com.aliyun.slb20140515.models.DescribeRulesResponse;
import com.aliyun.slb20140515.models.DescribeRulesResponseBody.DescribeRulesResponseBodyRulesRule;
import com.aliyun.slb20140515.models.DescribeVServerGroupAttributeRequest;
import com.aliyun.slb20140515.models.DescribeVServerGroupAttributeResponse;
import com.aliyun.slb20140515.models.DescribeVServerGroupAttributeResponseBody.DescribeVServerGroupAttributeResponseBodyBackendServersBackendServer;
import com.aliyun.slb20140515.models.DescribeVServerGroupsRequest;
import com.aliyun.slb20140515.models.DescribeVServerGroupsResponse;
import com.aliyun.slb20140515.models.DescribeVServerGroupsResponseBody.DescribeVServerGroupsResponseBodyVServerGroupsVServerGroup;
import com.aliyun.slb20140515.models.RemoveVServerGroupBackendServersRequest;
import com.aliyun.slb20140515.models.RemoveVServerGroupBackendServersResponse;
import com.beust.jcommander.internal.Lists;
import com.swift.api.aliyun.client.ClbClient;
import com.swift.exception.extend.SystemException;
import com.swift.register.alclb.model.BackendServer;
import com.swift.register.alclb.model.ClbRule;
import com.swift.util.type.JsonUtil;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2021年9月13日
 */
@Component
public class ClbApi {
    //private static Logger log = LoggerFactory.getLogger(ClbApi.class);
    @Autowired
    private ClbClient clbClient;
    
    @Value("${aliyun.register.clb:}")
    private String clbid;
    
    @Value("${aliyun.RegionId:}")
    private String regionId;
    /**
     * 增加虚拟服务器组服务器
     * @param vServerGroupId
     * @param backendServer
     */
    public void addVServerGroupBackendServers(String vServerGroupId,BackendServer backendServer) {
        try {
            AddVServerGroupBackendServersRequest req = new AddVServerGroupBackendServersRequest();
            req.setRegionId(regionId);
            req.setVServerGroupId(vServerGroupId);
            req.setBackendServers(JsonUtil.toJson(Lists.newArrayList(backendServer)));
            AddVServerGroupBackendServersResponse res = clbClient.getClient().addVServerGroupBackendServers(req);
            if(res==null) throw new SystemException("新增虚拟服务器组服务器异常");
            if(res.getBody()==null) throw new SystemException("新增虚拟服务器组服务器异常");
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    /**
     * 删除虚拟服务器组服务器
     * @param vServerGroupId
     * @param backendServer
     */
    public void removeVServerGroupBackendServers(String vServerGroupId,BackendServer backendServer) {
        try {
            RemoveVServerGroupBackendServersRequest req = new RemoveVServerGroupBackendServersRequest();
            req.setRegionId(regionId);
            req.setVServerGroupId(vServerGroupId);
            req.setBackendServers(JsonUtil.toJson(Lists.newArrayList(backendServer)));
            RemoveVServerGroupBackendServersResponse res = clbClient.getClient().removeVServerGroupBackendServers(req);
            if(res==null) throw new SystemException("删除虚拟服务器组服务器异常");
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    /**
     * 虚拟服务器组服务器
     * @param vServerGroupId
     * @return
     */
    public List<DescribeVServerGroupAttributeResponseBodyBackendServersBackendServer> getDescribeVServerGroupAttribute(String vServerGroupId){
        try {
            DescribeVServerGroupAttributeRequest req = new DescribeVServerGroupAttributeRequest();
            req.setRegionId(regionId);
            req.setVServerGroupId(vServerGroupId);
            DescribeVServerGroupAttributeResponse res = clbClient.getClient().describeVServerGroupAttribute(req);
            if(res==null)  return null;
            if(res.getBody()==null) return null;
            return res.getBody().getBackendServers().getBackendServer();
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    
    /**
     * 检测虚拟服务器组是否存在，不存在创建，存在直接返回
     * @param sysId
     * @return
     */
    public String autoVServerGroup(String sysId) {
        List<DescribeVServerGroupsResponseBodyVServerGroupsVServerGroup> list = getDescribeVServerGroups();
        if(TypeUtil.isNull(list)) return createVServerGroup(sysId);
        for(DescribeVServerGroupsResponseBodyVServerGroupsVServerGroup group : list) {
            if(sysId.equals(group.getVServerGroupName())) {
                return group.getVServerGroupId();
            }
        }
        return createVServerGroup(sysId);
    }
    
    /**
     * 创建虚拟服务器组
     * @param sysId
     * @return 服务器组ID
     */
    public String createVServerGroup(String sysId) {
        try {
            CreateVServerGroupRequest req = new CreateVServerGroupRequest();
            req.setLoadBalancerId(clbid);
            req.setRegionId(regionId);
            req.setVServerGroupName(sysId);
            CreateVServerGroupResponse res = clbClient.getClient().createVServerGroup(req);
            if(res==null)  return null;
            if(res.getBody()==null) return null;
            return res.getBody().getVServerGroupId();
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    /**
     * 得到所有虚拟服务器组
     */
    public List<DescribeVServerGroupsResponseBodyVServerGroupsVServerGroup> getDescribeVServerGroups() {
        try {
            DescribeVServerGroupsRequest req = new DescribeVServerGroupsRequest();
            req.setLoadBalancerId(clbid);
            req.setRegionId(regionId);
            DescribeVServerGroupsResponse res = clbClient.getClient().describeVServerGroups(req);
            if(res==null)  return null;
            if(res.getBody()==null) return null;
            if(TypeUtil.isNull(res.getBody().getVServerGroups())) return null;
            return res.getBody().getVServerGroups().getVServerGroup();
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    /**
     * 判断是否存在转发规则，不存在则创建
     * @param port
     * @param clbRule
     */
    public void autoRules(int port,ClbRule clbRule) {
        //需要在控制台内已创建监听端口
        List<DescribeRulesResponseBodyRulesRule> ruleList = getDescribeRules(port);
        if(TypeUtil.isNull(ruleList)) createRules(port, clbRule);
        for(DescribeRulesResponseBodyRulesRule rule:ruleList) {
            if(rule.getDomain().equals(clbRule.getDomain()) && TypeUtil.isNull(rule.getUrl())) {
                return;
            }
        }
        createRules(port, clbRule);
    }
    
    
    /**
     * 创建监听
     * @return RuleId
     */
    public String createRules(int port,ClbRule clbRule) {
        try {
            CreateRulesRequest req = new CreateRulesRequest();
            req.setLoadBalancerId(clbid);
            req.setListenerPort(port);
            req.setRegionId(regionId);
            req.setRuleList(JsonUtil.toJson(Lists.newArrayList(clbRule)));
            CreateRulesResponse res = clbClient.getClient().createRules(req);
            if(res==null)  throw new SystemException("创建监听失败");
            if(res.getBody()==null)  throw new SystemException("创建监听失败");
            if(TypeUtil.isNull(res.getBody().getRules()))  throw new SystemException("创建监听失败");
            return res.getBody().getRules().getRule().get(0).getRuleId();
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
    
    /**
     * 转发规则详情
     * @param port
     */
    public List<DescribeRulesResponseBodyRulesRule> getDescribeRules(int port) {
        try {
            DescribeRulesRequest req = new DescribeRulesRequest();
            req.setLoadBalancerId(clbid);
            req.setListenerPort(port);
            req.setRegionId(regionId);
            DescribeRulesResponse res = clbClient.getClient().describeRules(req);
            if(res==null) return null;
            if(res.getBody()==null) return null;
            if(TypeUtil.isNull(res.getBody().getRules())) return null;
            return res.getBody().getRules().getRule();
        }catch (Exception e) {
            throw new SystemException("请求阿里服务器API异常：",e);
        }
    }
}
